package com.situ.myboot.service.impl;

import com.situ.myboot.mapper.UserMapper;
import com.situ.myboot.pojo.User;
import com.situ.myboot.pojo.query.UserQuery;
import com.situ.myboot.service.IUserService;
import com.situ.myboot.util.JSONResult;
import com.situ.myboot.util.LayUITableJSONResult;
import com.situ.myboot.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

// IUserService userService = new UserServiceImpl()
@Service
public class UserServiceImpl implements IUserService {

    // IUserDao userDao
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public LayUITableJSONResult selectByPage(UserQuery userQuery) {
        int offset = (userQuery.getPage() - 1) * userQuery.getLimit();
        //查询当前页的数据
        List<User> list = userMapper.selectByPage(offset, userQuery.getLimit(), userQuery);
        //查询总的数量
        int totalCount = userMapper.selectTotalCount(userQuery);

        return LayUITableJSONResult.ok(totalCount, list);
    }

    @Override
    public JSONResult deleteById(Integer id) {
        int count = userMapper.deleteById(id);
        return count == 1 ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
    }

    @Override
    public JSONResult deleteAll(Integer[] ids) {
        // delete from user where id in(2, 3)
        int count = userMapper.deleteAll(ids);
        return count == ids.length ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
    }

    @Override
    public JSONResult add(User user) {
        user.setPassword(MD5Util.MD5Encode(user.getPassword()));
        int count = userMapper.add(user);
        return count == 1 ? JSONResult.ok("添加成功") : JSONResult.error("添加失败");
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public JSONResult update(User user) {
        int count = userMapper.update(user);
        return count == 1 ? JSONResult.ok("修改成功") : JSONResult.error("修改失败");
    }

    @Override
    public User login(String name, String password) {
        return userMapper.login(name, MD5Util.MD5Encode(password));
    }
}
